package com.dylan.channel.v5;

import java.io.IOException;
import java.nio.channels.*;

public abstract class SingleThreadEventLoop extends SingleThreadEventExecutor implements EventLoop {

    public void register(SelectableChannel channel) {
        if (inEventLoop(Thread.currentThread())) {
            register00((SocketChannel) channel);
        } else {
            this.execute(new Runnable() {
                @Override
                public void run() {
                    register0((ServerSocketChannel) channel);
                }
            });
        }
    }

    private void register0(ServerSocketChannel channel) {
        try {
            channel.configureBlocking(false);
            channel.register(getSelect(), SelectionKey.OP_ACCEPT);
        } catch (Exception e) {
            logger.warning(e.getMessage());
        }
    }

    private void register00(SocketChannel channel) {
        try {
            channel.configureBlocking(false);
            channel.register(getSelect(), SelectionKey.OP_READ);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected abstract Selector getSelect();

    @Override
    public EventLoop next() {
        return this;
    }

}
